package com.axend.sofa.adapter

import android.view.MotionEvent
import androidx.core.content.ContextCompat
import com.axend.lib_base.bean.BleDeviceEntity
import com.axend.lib_base.ext.click
import com.axend.lib_service.Constant
import com.axend.sofa.R
import com.axend.sofa.databinding.AdapterBleDeviceItemBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import dagger.hilt.android.scopes.ActivityScoped
import javax.inject.Inject

/**
 * 设备列表适配器
 */
@ActivityScoped
class BleDeviceAdapter @Inject constructor() :
    BaseQuickAdapter<BleDeviceEntity, BaseDataBindingHolder<AdapterBleDeviceItemBinding>>(
        R.layout.adapter_ble_device_item
    ) {

    private var onItemSelect: OnItemSelectListener? = null

    interface OnItemSelectListener {
        fun onItemSelectClick(position: Int)
    }

    init {
        addChildClickViewIds(R.id.cl_parent)
    }


    override fun convert(
        holder: BaseDataBindingHolder<AdapterBleDeviceItemBinding>,
        item: BleDeviceEntity
    ) {
        holder.dataBinding?.apply {
            tvDeviceName.text = "${item.bleDevice.bleName} : ${item.bleDevice.bleAddress}"
            tvRssi.text = "${item.rssi} dBm"
//            clParent.click { onItemSelect?.onItemSelectClick(holder.absoluteAdapterPosition) }
            progressBarItem.visibility = if (item.connectLoading) {
                android.view.View.VISIBLE
            } else {
                android.view.View.INVISIBLE
            }
            tvDeviceName.setTextColor(
                if (item.isSelect) {
                    context.getColor(com.axend.lib_base.R.color.colorPrimary)
                } else {
                    context.getColor(com.axend.lib_base.R.color.black)
                }
            )
            ivSelect.visibility = if (item.isSelect) {
                android.view.View.VISIBLE
            } else {
                android.view.View.INVISIBLE
            }
            if (data.size > 0 && holder.absoluteAdapterPosition == data.size - 1) {
                vLine.visibility = android.view.View.GONE
            } else {
                vLine.visibility = android.view.View.VISIBLE
            }
        }
    }

    /**
     * 局部刷新方法
     */
    override fun convert(
        holder: BaseDataBindingHolder<AdapterBleDeviceItemBinding>,
        item: BleDeviceEntity,
        payloads: List<Any>
    ) {
        super.convert(holder, item, payloads)
        //局部刷新
        for (playObj in payloads) {
            if (playObj == Constant.PLAY_LOAD_REFRESH_SELECT) {

            }
        }
    }


    fun setOnItemSelectListener(listener: (Int) -> Unit) {
        this.onItemSelect = object : OnItemSelectListener {
            override fun onItemSelectClick(position: Int) {
                listener(position)
            }
        }
    }
}